import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Card,
  Row,
  Col,
  Descriptions,
  DatePicker,
  Popconfirm,
  Divider
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  TruckOutlined,
  CloseOutlined,
  ExportOutlined
} from '@ant-design/icons';
import { orderAPI } from '../../services/api';
import { useAdminAuth } from '../../hooks/useAuth';

const { Option } = Select;
const { RangePicker } = DatePicker;

const AdminOrders = () => {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchForm] = Form.useForm();
  const [shipForm] = Form.useForm();
  const [detailVisible, setDetailVisible] = useState(false);
  const [shipVisible, setShipVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState(null);
  const { hasAdminPermission } = useAdminAuth();

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadOrders();
  }, []);

  const loadOrders = async (params = {}) => {
    setLoading(true);
    try {
      const response = await orderAPI.getOrders({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      });
      
      if (response.success) {
        setOrders(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }));
      }
    } catch (error) {
      message.error('加载订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadOrders(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadOrders();
  };

  const handleViewDetail = (order) => {
    setSelectedOrder(order);
    setDetailVisible(true);
  };

  const handleShip = (order) => {
    setSelectedOrder(order);
    shipForm.resetFields();
    setShipVisible(true);
  };

  // 修改后的 handleShipSubmit 函数
  const handleShipSubmit = async () => {
    try {
      const values = await shipForm.validateFields();
      
      // 更新订单的完整信息，包括物流信息和状态
      const updatedOrderData = {
        status: 'shipped',
        logistics: values.logistics,
        trackingNumber: values.trackingNumber,
        shipRemark: values.remark,
        shipTime: Date.now()
      };
      
      // 调用新的 updateOrder API 方法
      const response = await orderAPI.updateOrder(selectedOrder.id, updatedOrderData);
      
      if (response.success) {
        message.success('发货成功');
        setShipVisible(false);
        loadOrders();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('发货失败');
    }
  };

  const handleCancel = async (orderId) => {
    try {
      const response = await orderAPI.updateOrderStatus(orderId, 'cancelled');
      if (response.success) {
        message.success('订单已取消');
        loadOrders();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('取消订单失败');
    }
  };

  const getStatusConfig = (status) => {
    const statusMap = {
      pending: { color: 'orange', text: '待支付' },
      paid: { color: 'blue', text: '已支付' },
      shipped: { color: 'purple', text: '已发货' },
      delivered: { color: 'green', text: '已完成' },
      cancelled: { color: 'red', text: '已取消' }
    };
    return statusMap[status] || { color: 'default', text: status };
  };

  // 获取物流信息
  const getLogisticsInfo = (order) => {
    if (!order.logistics || !order.trackingNumber) {
      return {
        company: '无',
        trackingNumber: '无',
        shipTime: '无'
      };
    }
    
    return {
      company: order.logistics,
      trackingNumber: order.trackingNumber,
      shipTime: order.shipTime ? new Date(order.shipTime).toLocaleString() : '无'
    };
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 80,
    },
    {
      title: '商品数量',
      dataIndex: 'items',
      key: 'itemCount',
      render: (items) => items?.length || 0,
      width: 120,
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount) => `¥${amount?.toFixed(2) || '0.00'}`,
      sorter: true,
      width: 200,
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      render: (method) => method || '在线支付',
      width: 120,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const config = getStatusConfig(status);
        return <Tag color={config.color}>{config.text}</Tag>;
      },
      width: 120,
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => new Date(time).toLocaleString(),
      sorter: true,
      width: 200,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            size="small"
            onClick={() => handleViewDetail(record)}
            style={buttonStyle}
          >
            查看
          </Button>
          
          {hasAdminPermission('order:ship') && record.status === 'paid' && (
            <Button
              type="link"
              icon={<TruckOutlined />}
              size="small"
              onClick={() => handleShip(record)}
              style={buttonStyle}
            >
              发货
            </Button>
          )}
          
          {hasAdminPermission('order:cancel') && ['pending', 'paid'].includes(record.status) && (
            <Popconfirm
              title="确定要取消这个订单吗？"
              onConfirm={() => handleCancel(record.id)}
            >
              <Button
                type="link"
                danger
                icon={<CloseOutlined />}
                size="small"
                style={buttonStyle}
              >
                取消
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="orderNo" label="订单号">
                <Input placeholder="请输入订单号" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="userName" label="用户">
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="选择状态" allowClear>
                  <Option value="pending">待支付</Option>
                  <Option value="paid">已支付</Option>
                  <Option value="shipped">已发货</Option>
                  <Option value="delivered">已送达</Option>
                  <Option value="cancelled">已取消</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SearchOutlined />}
                  style={buttonStyle}
                >
                  搜索
                </Button>
                <Button onClick={handleReset} style={buttonStyle}>重置</Button>
              </Space>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="dateRange" label="下单时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label=" " colon={false}>
                <Button icon={<ExportOutlined />} style={buttonStyle}>
                  导出订单
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card title="订单管理">
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadOrders({ page, pageSize });
            },
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 订单详情模态框 */}
      <Modal
        title="订单详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)} style={buttonStyle}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedOrder && (
          <div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="订单号">
                {selectedOrder.orderNo}
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={getStatusConfig(selectedOrder.status).color}>
                  {getStatusConfig(selectedOrder.status).text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="用户">
                {selectedOrder.userName}
              </Descriptions.Item>
              <Descriptions.Item label="联系电话">
                {selectedOrder.userPhone || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="收货地址" span={2}>
                {selectedOrder.address || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="支付方式">
                {selectedOrder.paymentMethod || '在线支付'}
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">
                ¥{selectedOrder.totalAmount?.toFixed(2) || '0.00'}
              </Descriptions.Item>
              <Descriptions.Item label="下单时间">
                {new Date(selectedOrder.createTime).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="支付时间">
                {selectedOrder.payTime ? 
                  new Date(selectedOrder.payTime).toLocaleString() : '-'}
              </Descriptions.Item>
            </Descriptions>
            
            <Divider orientation="left" style={{ marginTop: 24, marginBottom: 16 }}>
              快递信息
            </Divider>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="物流公司">
                {getLogisticsInfo(selectedOrder).company}
              </Descriptions.Item>
              <Descriptions.Item label="运单号">
                {getLogisticsInfo(selectedOrder).trackingNumber}
              </Descriptions.Item>
              <Descriptions.Item label="发货时间" span={2}>
                {getLogisticsInfo(selectedOrder).shipTime}
              </Descriptions.Item>
              {selectedOrder.shipRemark && (
                <Descriptions.Item label="发货备注" span={2}>
                  {selectedOrder.shipRemark}
                </Descriptions.Item>
              )}
            </Descriptions>
            
            <Divider orientation="left" style={{ marginTop: 24, marginBottom: 16 }}>
              商品清单
            </Divider>
            <Table
              columns={[
                { title: '商品名称', dataIndex: 'name', key: 'name' },
                { title: '规格', dataIndex: 'spec', key: 'spec' },
                { title: '单价', dataIndex: 'price', key: 'price', render: (price) => `¥${price}` },
                { title: '数量', dataIndex: 'quantity', key: 'quantity' },
                { 
                  title: '小计', 
                  key: 'subtotal',
                  render: (_, record) => `¥${(record.price * record.quantity).toFixed(2)}`
                }
              ]}
              dataSource={selectedOrder.items || []}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </div>
        )}
      </Modal>

      {/* 发货模态框 */}
      <Modal
        title="订单发货"
        open={shipVisible}
        onOk={handleShipSubmit}
        onCancel={() => setShipVisible(false)}
        destroyOnClose
        okButtonProps={{ style: buttonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <Form form={shipForm} layout="vertical">
          <Form.Item
            name="logistics"
            label="物流公司"
            rules={[{ required: true, message: '请选择物流公司' }]}
          >
            <Select placeholder="请选择物流公司">
              <Option value="顺丰速运">顺丰速运</Option>
              <Option value="中通快递">中通快递</Option>
              <Option value="圆通速递">圆通速递</Option>
              <Option value="申通快递">申通快递</Option>
              <Option value="韵达速递">韵达速递</Option>
              <Option value="百世汇通">百世汇通</Option>
              <Option value="京东物流">京东物流</Option>
              <Option value="德邦物流">德邦物流</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="trackingNumber"
            label="运单号"
            rules={[{ required: true, message: '请输入运单号' }]}
          >
            <Input placeholder="请输入运单号" />
          </Form.Item>
          
          <Form.Item name="remark" label="发货备注">
            <Input.TextArea rows={3} placeholder="发货备注（可选）" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminOrders;